package io.ai.arch.java.ai;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.*;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

@Slf4j
@Service
public class NovelAnalysisService {

    private static final int CHUNK_CHAR_LIMIT = 2000; // 每段最多 2000 字符（安全范围）

    private final ChatClient chatClient;

    public NovelAnalysisService(ChatModel cm) {
        chatClient = ChatClient.create(cm);
    }

    public List<String> analyzeNovel(Path filePath) throws Exception {
        String fullText = Files.readString(filePath);

        List<String> chunks = splitIntoChunks(fullText, CHUNK_CHAR_LIMIT);

        List<String> results = new ArrayList<>();

        for (int i = 0; i < chunks.size(); i++) {
            String chunk = chunks.get(i);

            Prompt prompt = new Prompt(List.of(
                new SystemMessage("你是一个中文小说分析专家，擅长长篇小说理解。 "),
                new UserMessage("请用中文对以下小说片段进行剧情总结、主要人物与事件提取：\n\n" + chunk)
            ));

            ChatResponse response = chatClient.prompt(prompt).call().chatResponse();
            String result = response.getResult().getOutput().getText();
            results.add("【第" + (i + 1) + "段分析】\n" + result);
            log.info("result:{} ", result);
        }

        return results;
    }

    private List<String> splitIntoChunks(String text, int maxChunkSize) {
        List<String> chunks = new ArrayList<>();
        int length = text.length();
        for (int i = 0; i < length; i += maxChunkSize) {
            chunks.add(text.substring(i, Math.min(length, i + maxChunkSize)));
        }
        return chunks;
    }
}
